package com.nulldev.util.web.YouTubeExtractor.signatures;

import java.util.function.Function;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.VariableAPI.MathUtil.TimeUtil;
import com.nulldev.util.VariableAPI.RandomUtil;
import com.nulldev.util.data.CachedItem;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.YouTubeExtractor.signatures.extractor.Extractor;

public class CachedSignatureExtractor extends CachedItem<Extractor> {

	private static final Logger log = LoggerFactory
			.getLoggerD(Arguments.hasArgument("--debug", "-debug", "--trace", "--SignatureUpdates.debug", "--SignatureExtractor.debug"));

	public CachedSignatureExtractor() {
		super("YTE_CSE", TimeUtil.fromMinutes(60 + RandomUtil.randInt(-5, 5)), false, true);
	}

	@Override
	public Extractor accquire() throws Exception {
		log.debug("accquire()");
		final ExtractedSignatureData esd = SignatureExtractor.autoVideoID(null);
		log.debug("accquire:esd: " + esd);
		final Extractor extractor = SignatureExtractor.autoExtractor(esd);
		log.info("accquire:extractor: " + extractor);
		return extractor;
	}

	public void then(final Function<Extractor, Object> object) {
		object.apply(this.getAuto());
	}

	public Extractor assistedGet(final String result) {
		try {
			final String playerURL = SignatureExtractor.getPlayerURL(result);
			SignatureExtractor.cachedPlayerURL.set(playerURL);
			SignatureUpdates.setCachedPlayerURL(playerURL);
			return set(SignatureExtractor.extractor(SignatureExtractor.fromData(result, playerURL)));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
